package middleware

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"zhanyan/pac/util"
)

var allowPath = []string{"/user/addTeacher", "/user/addStudent", "/login"}

// JWTAuth 用于身份认证
func JWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		if !util.StringInSlice(c.Request.URL.Path, allowPath) &&
			!util.Regexp(c.Request.URL.Path, `/\w+/ws`) {
			auth := c.Request.Header.Get("Authorization")
			auth = util.DeleteBearer(auth)
			if len(auth) == 0 {
				c.Abort()
				c.String(http.StatusOK, "未登录无权限")
				return
			}
			// 校验token，只要出错直接拒绝请求
			_, err := util.ParseToken(auth)
			if err != nil {
				c.Abort()
				message := err.Error()
				c.JSON(http.StatusOK, message)
				return
			} else {
				//验证成功之后的操作
				//println("token 正确")
			}
		}
		c.Next()
	}
}
